package com.micro.school.order.service.impl;

import com.micro.school.common.core.constant.PayConstants;
import com.micro.school.common.core.context.SecurityContextHolder;
import com.micro.school.common.core.domain.R;
import com.micro.school.common.core.utils.StringUtils;
import com.micro.school.order.entity.*;
import com.micro.school.order.mapper.*;
import com.micro.school.order.service.IPayStudentFeeService;
import com.micro.school.order.service.PayOrderImportService;
import com.micro.school.order.util.OrderNoGenerator;
import com.micro.school.order.vo.PayStudentFeeVo;
import com.micro.school.system.api.RemoteEduService;
import com.micro.school.system.api.RemoteUserService;
import com.micro.school.system.api.domain.StudentInfos;
import com.micro.school.system.api.domain.vo.*;
import com.micro.school.system.api.factory.RemoteFileFallbackFactory;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("PayOrderImportServiceImpl")
public class PayOrderImportServiceImpl implements PayOrderImportService {

    @Resource
    private PayOrderImportMapper payOrderImportMapper;

    @Resource
    private PayOrderImportRecordMapper payOrderImportRecordMapper;
    @Resource
    private PayStudentFeeItemMapper payStudentFeeItemMapper;

    @Resource
    private PayFeeItemConfigMapper payFeeItemConfigMapper;

    @Resource
    private PayStudentFeeMapper payStudentFeeMapper;

    @Autowired
    private RemoteEduService remoteEduService;



    @Resource
    private RemoteUserService remoteUserService;


    private static final Logger log = LoggerFactory.getLogger(PayOrderImportServiceImpl.class);



    @Override
    public List<PayOrderImport> selectPayOrderImportList(PayOrderImport payOrderImport) {
        return payOrderImportMapper.queryAllByLimit(payOrderImport);
    }

    @Override
    public void insertOrderImport(PayOrderImport payOrderImport, String status) {

        if (status != null && !"".equals(status)){
            payOrderImport.setImportStatus(20);
        }else{
            payOrderImport.setImportStatus(10);
        }
        payOrderImportMapper.insert(payOrderImport);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String repeatUpload(String batchId) {
        if (StringUtils.isEmpty(batchId)) {
            return "批次号不能为空";
        }

        PayOrderImportRecord payOrderImportRecord = new PayOrderImportRecord();
        payOrderImportRecord.setBatchNum(batchId);
        payOrderImportRecord.setImportStatus(20);
        List<PayOrderImportRecord> payOrderImportRecordList = payOrderImportRecordMapper.queryAllByLimit(payOrderImportRecord);
        if (payOrderImportRecordList != null && !payOrderImportRecordList.isEmpty()) {
            return "有错误数据，重新导入失败！";
        } else {
            PayOrderImportRecord payOrderImportRecord1 = new PayOrderImportRecord();
            payOrderImportRecord1.setBatchNum(batchId);
            payOrderImportRecord1.setImportStatus(10);
            List<PayOrderImportRecord> payOrderImportRecords = payOrderImportRecordMapper.queryAllByLimit(payOrderImportRecord1);

            if (payOrderImportRecords == null || payOrderImportRecords.isEmpty()) {
                return "没有可导入的数据";
            }

            // 预先加载所有需要的费用项目配置，避免在循环中重复查询数据库
            List<PayFeeItemConfig> allFeeItemConfigs = payFeeItemConfigMapper.selectPayFeeItemConfigList(new PayFeeItemConfig());
            Map<String, PayFeeItemConfig> feeItemConfigMap = allFeeItemConfigs.stream()
                    .collect(Collectors.toMap(PayFeeItemConfig::getItemName, config -> config, (existing, replacement) -> existing));

            // 按学生姓名分组处理
            Map<String, List<PayOrderImportRecord>> recordsByStudent = payOrderImportRecords.stream()
                    .collect(Collectors.groupingBy(PayOrderImportRecord::getStudentName));
            // 遍历每个学生组
            for (Map.Entry<String, List<PayOrderImportRecord>> entry : recordsByStudent.entrySet()) {

                String generateOrderNo = OrderNoGenerator.generateOrderNo();
                List<PayOrderImportRecord> studentRecords = entry.getValue();
                // 使用第一个记录作为学生基本信息来源
                PayOrderImportRecord firstRecord = studentRecords.get(0);

                // 增加基础字段校验，发现空值直接返回错误信息
                if (StringUtils.isEmpty(firstRecord.getStudentName())) {
                    return "学生姓名不能为空，批次号: " + batchId;
                }

                if (StringUtils.isEmpty(firstRecord.getIdNumber())) {
                    return "学生身份证号不能为空，批次号: " + batchId;
                }

                if (StringUtils.isEmpty(firstRecord.getFeeYear())) {
                    return "学年信息不能为空，批次号: " + batchId;
                }

                if (StringUtils.isEmpty(firstRecord.getCollegeName())) {
                    return "学院名称不能为空，批次号: " + batchId;
                }

                if (StringUtils.isEmpty(firstRecord.getModelName())) {
                    return "培养模式不能为空，批次号: " + batchId;
                }

                if (StringUtils.isEmpty(firstRecord.getMajorName())) {
                    return "专业名称不能为空，批次号: " + batchId;
                }

                if (StringUtils.isEmpty(firstRecord.getGradeName())) {
                    return "年级信息不能为空，批次号: " + batchId;
                }

                if (StringUtils.isEmpty(firstRecord.getFeeItemConfigName())) {
                    return "收费项目名称不能为空，批次号: " + batchId;
                }

                PayStudentFee payStudentFees = new PayStudentFee();
                payStudentFees.setStudentName(firstRecord.getStudentName());
                payStudentFees.setIdNumber(firstRecord.getIdNumber());
                payStudentFees.setFeeYear(firstRecord.getFeeYear());
                payStudentFees.setTenantId(Integer.valueOf(SecurityContextHolder.getUserTenantId()));
                List<PayStudentFeeVo> payStudentFeeVos = payStudentFeeMapper.selectNoPayStudent(payStudentFees);

                // 使用事务确保数据一致性
                Long oldStudentFeeId = null;
                if (payStudentFeeVos != null && !payStudentFeeVos.isEmpty()) {
                    // 如果有未支付记录就直接替换掉
                    oldStudentFeeId = Long.valueOf(payStudentFeeVos.get(0).getId());
                    payStudentFeeMapper.deleteById(Math.toIntExact(oldStudentFeeId));
                    payStudentFeeItemMapper.deleteByStudentFeeId(oldStudentFeeId);
                }

                // 创建学生收费主表记录
                PayStudentFee payStudentFee = new PayStudentFee();
                // 验证学院信息
                SchoolCollegeVos schoolCollegeVos = new SchoolCollegeVos();
                schoolCollegeVos.setCollegeName(firstRecord.getCollegeName());
                schoolCollegeVos.setDeleteFlag("0");
                R<List<SchoolCollegeVos>> collegeResult = remoteEduService.checkCollege(schoolCollegeVos);

                // 校验学院信息返回结果
                if (collegeResult == null || collegeResult.getData() == null || collegeResult.getData().isEmpty()) {
                    return "未找到学院信息: " + firstRecord.getCollegeName();
                }

                SchoolCollegeVos college = collegeResult.getData().get(0);
                if (college == null) {
                    return "学院信息为空: " + firstRecord.getCollegeName();
                }

                payStudentFee.setCollegeId(college.getId());
                payStudentFee.setCampusId(college.getCampusId());
                payStudentFee.setCampusName(college.getCampusName());
                payStudentFee.setCollegeName(college.getCollegeName());

                // 验证学生信息
                StudentInfoVos studentInfoVos = new StudentInfoVos();
                studentInfoVos.setName(firstRecord.getStudentName());
                studentInfoVos.setIdNumber(firstRecord.getIdNumber());
                studentInfoVos.setIsDel(0);
                R<StudentInfos> studentResult = remoteUserService.queryStudent(studentInfoVos);

                // 校验学生信息返回结果
                if (studentResult == null || studentResult.getData() == null) {
                    return "未找到学生信息: " + firstRecord.getStudentName();
                }

                StudentInfos student = studentResult.getData();
                payStudentFee.setStudentId(Math.toIntExact(student.getId()));

                // 验证培养模式
                CollegeModelVos collegeModelVos = new CollegeModelVos();
                collegeModelVos.setModelName(firstRecord.getModelName());
                collegeModelVos.setCollegeName(firstRecord.getCollegeName());
                collegeModelVos.setCampusId(college.getCampusId());
                collegeModelVos.setDeleteFlag("0");
                collegeModelVos.setStatus("1");
                R<List<CollegeModelVos>> modelResult = remoteEduService.checkEducation(collegeModelVos);

                // 校验培养模式返回结果
                if (modelResult == null || modelResult.getData() == null || modelResult.getData().isEmpty()) {
                    return "未找到培养模式信息: " + firstRecord.getModelName();
                }

                payStudentFee.setModelId(modelResult.getData().get(0).getId());
                payStudentFee.setModelName(modelResult.getData().get(0).getModelName());

                // 验证专业信息
                CollegeMajorVos collegeMajorVos = new CollegeMajorVos();
                collegeMajorVos.setCollegeIds(String.valueOf(college.getId()));
                collegeMajorVos.setMajorName(firstRecord.getMajorName());
                collegeMajorVos.setDeleteFlag("0");
                collegeMajorVos.setStatus("1");
                R<List<CollegeMajorVos>> majorResult = remoteEduService.checkMajor(collegeMajorVos);

                // 校验专业信息返回结果
                if (majorResult == null || majorResult.getData() == null || majorResult.getData().isEmpty()) {
                    return "未找到专业信息: " + firstRecord.getMajorName();
                }

                payStudentFee.setMajorId(majorResult.getData().get(0).getId());
                payStudentFee.setMajorName(majorResult.getData().get(0).getMajorName());

                // 验证年级信息
                SchoolGradeVos schoolGradeVos = new SchoolGradeVos();
                schoolGradeVos.setGrade(firstRecord.getGradeName());
                schoolGradeVos.setDeleteFlag("0");
                schoolGradeVos.setStatus("1");
                R<List<SchoolGradeVos>> gradeResult = remoteEduService.checkGrade(schoolGradeVos);

                // 校验年级信息返回结果
                if (gradeResult == null || gradeResult.getData() == null || gradeResult.getData().isEmpty()) {
                    return "未找到年级信息: " + firstRecord.getGradeName();
                }

                payStudentFee.setGradeId(gradeResult.getData().get(0).getId());
                payStudentFee.setGradeName(firstRecord.getGradeName());

                // 验证收费项目
                PayFeeItemConfig payFeeItemConfig = new PayFeeItemConfig();
                payFeeItemConfig.setItemName(firstRecord.getFeeItemConfigName());
                payFeeItemConfig.setTenantId(Integer.valueOf(SecurityContextHolder.getUserTenantId()));
                payFeeItemConfig.setCloseStatus(PayConstants.YESORNO_Y);
                payFeeItemConfig.setDeleteFlag("0");
                List<PayFeeItemConfig> feeItemConfigs = payFeeItemConfigMapper.selectPayFeeItemConfigList(payFeeItemConfig);

                // 校验收费项目返回结果
                if (feeItemConfigs == null || feeItemConfigs.isEmpty()) {
                    return "未找到收费项目配置: " + firstRecord.getFeeItemConfigName();
                }

                PayFeeItemConfig feeItem = feeItemConfigs.get(0);
                payStudentFee.setSubjectId(Integer.valueOf(feeItem.getSubjectType()));
                payStudentFee.setProjectName(feeItem.getItemName());

                // 验证学年
                SchoolFeeYearVos schoolFeeYearVos = new SchoolFeeYearVos();
                schoolFeeYearVos.setDeleteFlag("0");
                schoolFeeYearVos.setTenantId(Long.valueOf(SecurityContextHolder.getUserTenantId()));
                schoolFeeYearVos.setStatus("1");
                schoolFeeYearVos.setIsCloseChannel("1");
                schoolFeeYearVos.setFeeYear(firstRecord.getFeeYear());
                R<List<SchoolFeeYearVos>> feeYearResult = remoteEduService.checkFeeYear(schoolFeeYearVos);

                // 校验学年返回结果
                if (feeYearResult == null || feeYearResult.getData() == null || feeYearResult.getData().isEmpty()) {
                    return "未找到学年信息: " + firstRecord.getFeeYear();
                }

                payStudentFee.setFeeYearId(Math.toIntExact(feeYearResult.getData().get(0).getId()));
                payStudentFee.setFeeYear(feeYearResult.getData().get(0).getFeeYear());

                // 填充学生基本信息
                payStudentFee.setBillNo(generateOrderNo);
                payStudentFee.setStudentName(firstRecord.getStudentName());
                payStudentFee.setIdNumber(firstRecord.getIdNumber());
                if (firstRecord.getStudentId() != null) {
                    payStudentFee.setStudentId(firstRecord.getStudentId().intValue());
                }

                payStudentFee.setGradeName(firstRecord.getGradeName());
                // 计算该学生的总金额（合并所有收费项目）
                double totalAmount = studentRecords.stream()
                        .mapToDouble(record -> record.getItemPrice() != null ?
                                record.getItemPrice().doubleValue() : 0.0)
                        .sum();
                payStudentFee.setAmountPayable(totalAmount);
                payStudentFee.setAmountPending(totalAmount);
                payStudentFee.setAmountPaid(0.0);
                payStudentFee.setAmountRefunded(0.0);
                payStudentFee.setAmountDeducted(0.0);

                // 状态信息
                payStudentFee.setBillStatus(10); // 默认未支付状态
                payStudentFee.setRefundStatus(10); // 默认未支付状态
                // 租户信息
                payStudentFee.setTenantId(Integer.valueOf(SecurityContextHolder.getUserTenantId()));
                // 删除标记
                payStudentFee.setDeleteFlag(firstRecord.getDeleteFlag());
                // 创建信息
                payStudentFee.setCreateDept(firstRecord.getCreateDept());
                payStudentFee.setCreateBy(firstRecord.getCreateBy());
                payStudentFee.setCreateTime(new Date());
                payStudentFee.setUpdateBy(firstRecord.getCreateBy());
                payStudentFee.setUpdateTime(new Date());
                // 保存学生收费主表记录
                payStudentFeeMapper.insert(payStudentFee);

                // 为该学生的所有收费记录创建明细项
                for (PayOrderImportRecord record : studentRecords) {
                    // 校验收费项目名称
                    if (StringUtils.isEmpty(record.getFeeItemConfigName())) {
                        return "收费项目名称不能为空，学生: " + record.getStudentName();
                    }

                    PayStudentFeeItem payStudentFeeItem = new PayStudentFeeItem();
                    // 关联主表ID
                    payStudentFeeItem.setBillNo(generateOrderNo);
                    payStudentFeeItem.setStudentFeeId(payStudentFee.getId());
                    // 收费项目配置信息
                    if (StringUtils.hasText(record.getFeeItemConfigName())) {
                        PayFeeItemConfig config = feeItemConfigMap.get(record.getFeeItemConfigName());
                        if (config != null) {
                            payStudentFeeItem.setFeeItemConfigId(config.getId().intValue());
                        }
                        payStudentFeeItem.setFeeItemConfigName(record.getFeeItemConfigName());
                    }
                    // 单价
                    if (record.getItemPrice() != null) {
                        payStudentFeeItem.setItemPrice(record.getItemPrice().doubleValue());
                    }
                    // 数量，默认为1
                    payStudentFeeItem.setItemQuantity(1);
                    // 小计金额
                    if (record.getItemPrice() != null) {
                        payStudentFeeItem.setTotalAmount(record.getItemPrice().doubleValue());
                    }
                    // 显示顺序
                    payStudentFeeItem.setOrderNum(0);
                    // 支付状态
                    payStudentFeeItem.setPayStatus(10); // 待支付
                    // 租户ID
                    payStudentFeeItem.setTenantId(Integer.valueOf(SecurityContextHolder.getUserTenantId()));
                    // 删除标记
                    payStudentFeeItem.setDeleteFlag("0");
                    // 创建部门
                    payStudentFeeItem.setCreateDept(record.getCreateDept());
                    // 创建者
                    payStudentFeeItem.setCreateBy(record.getCreateBy());
                    // 创建时间
                    payStudentFeeItem.setCreateTime(new Date());
                    // 更新者
                    payStudentFeeItem.setUpdateBy(record.getCreateBy());
                    // 更新时间
                    payStudentFeeItem.setUpdateTime(new Date());

                    payStudentFeeItem.setFeeItemConfigType(record.getFeeItemConfigType());
                    payStudentFeeItem.setMandatoryStatus(record.getMandatoryStatus());
                    // 保存学生收费明细记录
                    payStudentFeeItemMapper.insert(payStudentFeeItem);
                }
            }
            payOrderImportMapper.updateByBatchId(batchId);
        }
        return "重新导入成功";
    }

}
